package com.szjz.elasticsearch.biz.controller;

import com.alibaba.fastjson.JSON;
import com.szjz.elasticsearch.biz.entity.ESYyStyReturn;
import com.szjz.elasticsearch.biz.service.ESYyStyReturnService;
import com.szjz.elasticsearch.result.R;
import com.szjz.elasticsearch.eshelper.service.ESService;
import com.szjz.elasticsearch.eshelper.util.DateUtils;
import com.szjz.elasticsearch.eshelper.wrapper.ESQueryWrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author shibo
 * @desc
 * @date 2020/6/3 周三
 */

@Slf4j
@RestController
@RequestMapping("/admin/sty")
public class YyStyReturnController {

    @Autowired
    private ESYyStyReturnService esYyStyReturnService;
    @Autowired
    private ESService esService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @ApiOperation(value = "批量更新")
    @RequestMapping(value = "/updateBatch", method = RequestMethod.POST)
    public void saveBatch(@RequestParam Integer start,
                          @RequestParam Integer num,
                          @RequestParam String name
    ) {
        List<ESYyStyReturn> list = new ArrayList<>();
        for (int i = start; i <= num; i++) {
            String my_yy_sty_return = "{'id':'20201025012327|2eDrjkVdU1FrqVBPmUTj|32|1|375'" + i + i +
                    ",'areaId':'15337687','areaName':'上蔡县-" + num + "','fieldId':'15337689'," +
                    "'fieldName':'上蔡5场','segmentId':'13910','segmentName':'泌乳母猪'," +
                    "'fbatchId':'SC440636207446200621','fbatch':'上蔡5场|泌乳母猪|侯树敏|33;" +
                    "','unitId':'15337687|15337689|13910|33','unit':'33','age':" + i + ".00," +
                    "'bucketId':'15337687|15337689|13910|33|10','bucketNo':9," +
                    "'earNumber':'BS0000610236669201015|15392023|22|33'," +
                    "'styId':null,'styNo':null,'styFunctioncode':null,'stationNum':'1'," +
                    "'requirement':null,'actualSend':200.00,'status':2," +
                    "'crtTime':1636373400845,'updTime':1604451119000,'dataType':'my_base_fieldentry'," +
                    "'pigFormId':'15392023','exchangeStatus':1,'requirementTime':1603555200000," +
                    "'attr1':'3','attr2':'2','attr3':'0','attr4':'0','attr5':'1','attr6':'1'," +
                    "'attr7':'2eDrjkVdU1FrqVB2WPmUTj','attr8':'3751','attr9':null,'attr10':null," +
                    "'attr11':null,'attr12':null,'attr13':null,'attr14':0.00,'attr15':0.00}";
            ESYyStyReturn esYyStyReturn = JSON.parseObject(my_yy_sty_return, ESYyStyReturn.class);

            ESYyStyReturn styReturn = new ESYyStyReturn();
//            styReturn.setFieldName("测试场1---" + num);
//            styReturn.setAreaName("测试区1--" + num);
//            styReturn.setId(esYyStyReturn.getId() + "-" + i);
//            styReturn.setDocId(esYyStyReturn.getId() + "-" + i);

            String id = esYyStyReturn.getId();
            esYyStyReturn.setId(id + "-" + i);
            esYyStyReturn.setAreaName(esYyStyReturn.getAreaName() + name);
//            esYyStyReturn.setFieldName(esYyStyReturn.getFieldName() + name);
//            esYyStyReturn.setUnit(10+"");
            esYyStyReturn.setBucketNo(10);
            esYyStyReturn.setFieldName(esYyStyReturn.getFieldName() + "环境i" + i);
            list.add(esYyStyReturn);
        }
//        rabbitTemplate.convertAndSend("slcStyReturnFanOutExchangeBatch",null,list);
        esYyStyReturnService.saveOrUpdateBatch(list);
//         esYyStyReturnService.saveOrUpdate(list.get(0));
        //esYyStyReturnService.saveOrUpdateBatchByMonth(list);
//        esYyStyReturnService.delete(w);
    }

    @ApiOperation(value = "增加")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(@RequestParam Integer start, @RequestParam Integer num) {
        ESYyStyReturn ESYyStyReturn = null;
        if (num == 1) {
            ESYyStyReturn = (ESYyStyReturn) new ESYyStyReturn()
                    .setAreaId("" + num)
                    .setAreaName(num + "区域")
                    .setFieldId("" + num)
                    .setFieldName(num + "场次")
                    .setSegmentId("" + num)
                    .setSegmentName("工段" + num)
                    .setFbatch("批次" + num)
                    .setFbatchId(num + "")
                    .setId("00012");
        } else {
            ESYyStyReturn = (ESYyStyReturn) new ESYyStyReturn()
                    .setUnit(num + "单元")
                    .setUnitId("" + num)
                    .setBucketNo(num)
                    .setActualSend((double) num)
                    .setAttr6(String.valueOf(num % 6))
                    .setAttr2(String.valueOf(num % 10))
                    .setAge("" + num)
                    .setId("00012");
        }
        esYyStyReturnService.saveOrUpdate(ESYyStyReturn);
    }

    @ApiOperation(value = "删除索引库")
    @RequestMapping(value = "/deleteIndex", method = RequestMethod.DELETE)
    public void deleteIndex(String idxName) {
        esService.deleteIndex(idxName);
    }


    @ApiOperation(value = "根据id获取文档数据")
    @GetMapping(value = "/{id}")
    public R getById(@PathVariable("id") String id) {
        return R.success(esYyStyReturnService.selectByDocId(id));
    }


    @ApiOperation(value = "count")
    @GetMapping(value = "/count/t/{unitId}")
    public R count(@PathVariable("unitId") String unitId) {
        ESYyStyReturn esYyStyReturn = new ESYyStyReturn().setUnitId(unitId);
        return R.success(esYyStyReturnService.count(esYyStyReturn));
    }

    @ApiOperation(value = "countByUnitId--map")
    @GetMapping(value = "/count/map/{unitId}")
    public R countByUnitIdMap(@PathVariable("unitId") String unitId) {
        Map<String, Object> map = new HashMap<>();
        map.put("unitId", unitId);
        return R.success(esYyStyReturnService.count(map));
    }

    @ApiOperation(value = "countByUnitId--wrapper")
    @GetMapping(value = "/count/wrapper")
    public R countByUnitId(@RequestParam(value = "unitId", required = false) String unitId,
                           @RequestParam(value = "attr6", required = false) String attr6,
                           @RequestParam(value = "startDate", required = false) String startDate,
                           @RequestParam(value = "endDate", required = false) String endDate,
                           @RequestParam(value = "left", required = false) String left,
                           @RequestParam(value = "right", required = false) String right
    ) {
        //List<Object> strings = Arrays.asList(attr6.split(","));
        ESQueryWrapper<ESYyStyReturn> wrapper = new ESQueryWrapper<ESYyStyReturn>();
//        if (unitId != null) {
//            wrapper.eq(ESYyStyReturn::getUnitId, unitId);
//        }
//        //wrapper.in(ESYyStyReturn::getAttr6, strings);
//        if (startDate != null) {
        wrapper.gte(ESYyStyReturn::getCrtTime, DateUtils.parse(startDate + " 00:00:00", DateUtils.PATTERN_YYMMDDHHMMSS));
//        }
//        if (endDate != null) {
//            wrapper.lte(ESYyStyReturn::getCrtTime, DateUtils.parse(endDate + " 23:59:59", DateUtils.PATTERN_YYMMDDHHMMSS));
//        }
        if (left != null) {
            wrapper.likeLeft(ESYyStyReturn::getFieldName, left);
        }
        if (right != null) {
            wrapper.likeRight(ESYyStyReturn::getFieldName, right);
        }
        //esYyStyReturnService.selectAcDay(wrapper, new Date(),new Date());

//        return R.success(esYyStyReturnService.select(wrapper,DateUtils.parse("2020-01-12 00:00:00",DateUtils.PATTERN_YYMMDDHHMMSS)),
//                DateUtils.parse("2020-01-12 23:00:00",DateUtils.PATTERN_YYMMDDHHMMSS)));

        return null;
    }

    /**
     * 通过es包装类查询
     */
    @ApiOperation(value = "select--wrapper")
    @GetMapping(value = "/select/wrapper?aaa = ''")
    public R selectByWrapper(@RequestParam String unitId,
                             @RequestParam String attr6,
                             @RequestParam String startDate,
                             @RequestParam String endDate,
                             @RequestParam(required = false) String left,
                             @RequestParam(required = false) String right,
                             @RequestParam(required = false) String leftOne,
                             @RequestParam(required = false) String rightOne
    ) {

        long begin = System.currentTimeMillis();
        Date parse = DateUtils.parse(startDate + " 00:00:00", DateUtils.PATTERN_YYMMDDHHMMSS);
        Date parse1 = DateUtils.parse(endDate + " 23:59:59", DateUtils.PATTERN_YYMMDDHHMMSS);

        ESQueryWrapper<ESYyStyReturn> wrapper = new ESQueryWrapper<>();
        if (unitId != null) {
            //15323756|15391694|13906|7
            wrapper.eq(ESYyStyReturn::getUnitId, unitId);
        }
//        if (attr6 != null) {
//            wrapper.eq(ESYyStyReturn::getAttr6, attr6);
//        }
//        if (startDate != null) {
//            wrapper.gte(ESYyStyReturn::getCrtTime, parse.getTime());
//        }
//        if (endDate != null) {
//            wrapper.lte(ESYyStyReturn::getCrtTime, parse1.getTime());
//        }
//        if (left != null) {
//            wrapper.likeLeft(ESYyStyReturn::getFieldName, left);
//        }
//        if (right != null) {
//            wrapper.likeRight(ESYyStyReturn::getFieldName, right);
//        }
//        if (leftOne != null) {
//            wrapper.likeLeftOne(ESYyStyReturn::getFieldName, leftOne);
//        }
//        if (rightOne != null) {
//            wrapper.likeRightOne(ESYyStyReturn::getFieldName, rightOne);
//        }
//        wrapper.or(ESYyStyReturn::getFieldName, "河南");
//        wrapper.or(ESYyStyReturn::getBucketNo, 10);
//        wrapper.or(ESYyStyReturn::getUnit, 10);
//        wrapper.orLikeLeft(ESYyStyReturn::getFieldName, "22");
//        wrapper.orLikeRight(ESYyStyReturn::getAreaName, "30河南");

        wrapper.includeFields(ESYyStyReturn::getUnit, ESYyStyReturn::getBucketNo, ESYyStyReturn::getActualSend);
        // es分页查询
        List<ESYyStyReturn> esYyStyReturns = esYyStyReturnService.selectAcDay(wrapper, parse, parse1);
        long end1 = System.currentTimeMillis();
        String s = "耗费时间：" + (end1 - begin) + "ms    数据量：" + esYyStyReturns.size();
        log.info(s);
        return R.success(s);
    }

    /**
     * 通过包装类删除
     */
    @ApiOperation(value = "delete--wrapper")
    @GetMapping(value = "/delete/wrapper")
    public R deleteByWrapper(@RequestParam(value = "unitId") String unitId,
                             @RequestParam(value = "attr6", required = false) String attr6,
                             @RequestParam(value = "startDate", required = false) String startDate,
                             @RequestParam(value = "endDate", required = false) String endDate,
                             @RequestParam(value = "left", required = false) String left,
                             @RequestParam(value = "right", required = false) String right
    ) {

//        Date parse = DateUtils.parse(startDate + " 00:00:00", DateUtils.PATTERN_YYMMDDHHMMSS);
//        Date parse1 = DateUtils.parse(endDate + " 23:59:59", DateUtils.PATTERN_YYMMDDHHMMSS);
        ESQueryWrapper<ESYyStyReturn> wrapper = new ESQueryWrapper<ESYyStyReturn>();
        if (unitId != null) {
            wrapper.eq(ESYyStyReturn::getUnitId, unitId);
        }
        if (attr6 != null) {
            wrapper.eq(ESYyStyReturn::getAttr6, attr6);
        }
//        if (startDate != null) {
//            wrapper.gte(ESYyStyReturn::getCrtTime, parse.getTime());
//        }
//        if (endDate != null) {
//            wrapper.lte(ESYyStyReturn::getCrtTime, parse1.getTime());
//        }
        if (left != null) {
            wrapper.likeLeft(ESYyStyReturn::getFieldName, left);
        }
        if (right != null) {
            wrapper.likeRight(ESYyStyReturn::getFieldName, right);
        }
//        wrapper.likeLeft(ESYyStyReturn::getAreaName, "河南");
        return R.success(esYyStyReturnService.delete(wrapper));
    }


    @ApiOperation(value = "根据id 删除文档数据")
    @DeleteMapping(value = "/delete/{id}")
    public R delete(@PathVariable("id") String id) {
        return R.status(esYyStyReturnService.deleteByDocId(id));
    }


    @ApiOperation(value = "更新文档数据")
    @PutMapping(value = "/update/{id}")
    public R update(@PathVariable("id") String id,
                    @RequestParam String areaName) {
        boolean b = esYyStyReturnService.dataIsExist(id);
        if (!b) {
            return R.gone();
        }
        ESYyStyReturn esYyStyReturn = esYyStyReturnService.selectById(id).get(0);
        esYyStyReturn.setAreaName(areaName);
        Boolean update = esYyStyReturnService.saveOrUpdate(esYyStyReturn);
        return update ? R.success(esYyStyReturn) : R.fail();
    }


    @GetMapping("/create/{date}")
    @ApiOperation(value = "create", notes = "2020_10_01")
    public void create(@PathVariable("date") String date) {
        esService.createIndex("my_yy_sty_return-" + date, ESYyStyReturn.class);
    }

    /**
     * pc端饲喂详情列表
     */
    @GetMapping("/getPageList")
    @ApiOperation(value = "pc端饲喂详情列表", notes = "beginCreateDate/endCreateDate: 2020-05-22 11:50:09")
    public void getPageList(
            @ApiParam("场次") @RequestParam(required = false) String fieldId,
            @ApiParam("单元") @RequestParam(required = false) String unitId,
            @ApiParam("工段id") @RequestParam(required = false) String segmentId,
            @ApiParam("料筒id") @RequestParam(required = false) String bucketId,
            @ApiParam("【0】下料记录 【1】下水记录") @RequestParam(required = false) String attr6,
            @RequestParam(required = false) String beginCreateDate,
            @RequestParam(required = false) String endCreateDate,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "1") Integer current
    ) {
//        Page<ESYyStyReturn> pages = yyStyReturnService.getPageList(bucketId, fieldId,segmentId, unitId, attr6,
//                beginCreateDate, endCreateDate, size, current, count);
        if (org.apache.commons.lang3.StringUtils.isEmpty(fieldId)) {
            throw new RuntimeException("请选择场次");
        }
//        if (StringUtils.isEmpty(beginCreateDate) || StringUtils.isEmpty(endCreateDate)) {
//            throw new DataValidateErrorException("请选择时间");
//        }

        ESQueryWrapper<ESYyStyReturn> queryWrapper = new ESQueryWrapper<>();
        queryWrapper.eq(ESYyStyReturn::getFieldId, fieldId);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(segmentId)) {
            queryWrapper.eq(ESYyStyReturn::getSegmentId, segmentId);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(unitId)) {
            queryWrapper.eq(ESYyStyReturn::getUnitId, unitId);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(bucketId)) {
//            queryWrapper.eq(ESYyStyReturn::getBucketId, bucketId);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(attr6)) {
            queryWrapper.eq(ESYyStyReturn::getAttr6, attr6);
        }
        Date startTime = null;
        Date endTime = null;
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(beginCreateDate) && org.apache.commons.lang3.StringUtils.isNotEmpty(endCreateDate)) {
            String s = beginCreateDate.split(" ")[0] + " 00:00:00";
            String s1 = endCreateDate.split(" ")[0] + " 23:59:59";
            startTime = DateUtils.parse(s, DateUtils.PATTERN_YYMMDDHHMMSS);
            endTime = DateUtils.parse(s1, DateUtils.PATTERN_YYMMDDHHMMSS);
            queryWrapper.gte(ESYyStyReturn::getCrtTime, startTime.getTime());
            queryWrapper.lte(ESYyStyReturn::getCrtTime, endTime.getTime());
        }
        queryWrapper.orderByDesc(ESYyStyReturn::getCrtTime);
        queryWrapper.excludeFields(ESYyStyReturn::getCrtTime);
        queryWrapper.includeFields(ESYyStyReturn::getActualSend);
        List<Object> list = new ArrayList<>();
    }


}
